#include <webby/logging.hxx>
#include <webby/stdoutloglistener.hxx>

#include <sys/time.h>

using namespace webby;

Logging *Logging::mInstance = 0;

Logging &
Logging::instance()
{
	if ( mInstance == 0 )
	{
		mInstance = new Logging;
	}



	return *mInstance;
}

Logging::Logging() : mCurrentLevel( INFORMATIONAL ), mStartTime( 0 )
{
	addLogListener( LogListenerPtr( new StdOutLogListener ) );

	timeval tv;
	gettimeofday( &tv, NULL );
	mStartTime = ((double)tv.tv_sec + (double)tv.tv_usec/1000000.0f);
}

void 
Logging::addLogMessage( LogLevel level, double currentTime, const std::string &logMessage, const std::string &function, unsigned int lineNumber )
{
	for ( std::vector< LogListenerPtr >::iterator iter = mLogListeners.begin(); iter != mLogListeners.end(); ++iter)
	{
		(*iter)->onLogMessage( level, currentTime, logMessage, function, lineNumber );
	}
}

void
Logging::addLogListener( LogListenerPtr listener )
{
	mLogListeners.push_back( listener );
}

double
Logging::getCurrentTime() const
{
	timeval tv = {0};
	gettimeofday( &tv, NULL );
	double now = (double)tv.tv_sec + (double)tv.tv_usec/1000000.0f;
	double elapsed = now - mStartTime;
	return elapsed;
}
